package com.joven.shelltest.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.joven.shelltest.dto.EmployeeDto;
import com.joven.shelltest.entity.BankAccountModel;
import com.joven.shelltest.entity.MulAccountModel;
import com.joven.shelltest.entity.SignValueModel;
import com.joven.shelltest.listener.JovenListener;
import com.joven.shelltest.service.BankAccountService;
import com.joven.shelltest.service.MulAccountService;
import com.joven.shelltest.service.SignValueService;
import com.joven.shelltest.service.SysUserService;
import com.joven.shelltest.utils.RedisUtils;
import com.joven.shelltest.utils.SignUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author wzj
 * @Date 2023-08-17 16:50
 **/
@RestController
@RequestMapping("/hello")
@RequiredArgsConstructor
@Validated
public class OtherTestController {

    @GetMapping("/bean1")
    public Object getBean1(HttpServletRequest request) {
        //直接通过方法中的HttpServletRequest对象
        ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
        JovenListener jovenListener = (JovenListener) applicationContext.getBean("jovenListener");
        return jovenListener.toString();
    }

    @GetMapping("/bean2")
    public Object getBean2() {
        //手动获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());

        JovenListener jovenListener = (JovenListener) applicationContext.getBean("jovenListener");
        return jovenListener.toString();
    }

    /**
     * get请求 参数校验 类上加@Validated
     *
     * @param param
     * @return
     */
    @GetMapping("/testValidated")
    public String testValidated(@NotBlank(message = "param is null") String param) {
        return "validated:" + param;
    }

    private final RedisUtils redisUtils;

    @GetMapping("/testSetRedis")
    public Object testSetRedis() {
        EmployeeDto dto = new EmployeeDto();
        dto.setName("joven");
        dto.setSalary(15.25);
        dto.setDepartment("信安");
        dto.setIdCard("10086");
        redisUtils.set("joven_wong_one", dto);
//        String bak = (String) redisUtils.get("joven_wong_one");
//        EmployeeDto reObj = JSONObject.parseObject(bak, EmployeeDto.class);
        return redisUtils.get("joven_wong_one");
    }


    @GetMapping("/sign")
    public Map<String, Object> sign(Integer user, String dateStr) {
        return redisUtils.doSign(user, dateStr);
    }

    private final SysUserService sysUserService;

    @GetMapping("/usrList")
    public ResponseEntity<Object> usrList(Integer status) {
        return new ResponseEntity<>(sysUserService.getUsrByStatus(status), HttpStatus.OK);
    }

    private final BankAccountService bankAccountService;

    @GetMapping("/getId")
    public ResponseEntity<Object> getId() {
        BankAccountModel bankAccountModel = new BankAccountModel();
        bankAccountModel.setAccount("1111");
        bankAccountModel.setMobile("444444");
        bankAccountService.saveOrUpdate(bankAccountModel);
        return new ResponseEntity<>(bankAccountModel.getId(), HttpStatus.OK);
    }

    private final SignValueService signValueService;

    /**
     * 获取接口签名参数
     *
     * @return true/false
     */
    @GetMapping("/getAkSk")
    public Boolean getKey(String timeOut) {
        SignValueModel signValueModel = new SignValueModel();
        signValueModel.setAccessKey(SignUtils.generateAccessKey());
        signValueModel.setSecretKey(SignUtils.generateSecretKey());
        signValueModel.setScene(SignUtils.getNonceStr(8));
        signValueModel.setInvokeStatus("1");
        signValueModel.setTimeOut(timeOut);
        return signValueService.save(signValueModel);
    }

    /**
     * Request 异步线程传递 正确打开方式
     * @param request /
     * @param response /
     * @return /
     */
    @GetMapping("/getRequest")
    public String getRequest(HttpServletRequest request, HttpServletResponse response) {
        AsyncContext asyncContext = request.startAsync(request, response);
        String age = request.getParameter("age");
        System.out.println("age:" + age);
        new Thread(()-> {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String age1 = request.getParameter("age");
            System.out.println("age1:" + age1);
            asyncContext.complete();
        }).start();
        return "success";
    }

    @GetMapping("/doIncr")
    public ResponseEntity<Object> doIncr() {
        return new ResponseEntity<>(redisUtils.incr("count1"), HttpStatus.OK);
    }

    @GetMapping("/doDecr")
    public ResponseEntity<Object> doDecr() {
        return new ResponseEntity<>(redisUtils.decr("count1"), HttpStatus.OK);
    }

    @GetMapping("/clear")
    public ResponseEntity<Object> clear() {
        redisUtils.remove("count1");
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping("/expire")
    public ResponseEntity<Object> expire() {
        redisUtils.set("ip", "127.0.0.1");
        return new ResponseEntity<>(redisUtils.expire("ip", 60L), HttpStatus.OK);
    }

    @GetMapping("/hasKey")
    public ResponseEntity<Object> hasKey() {
        Map<String, Object> map = new HashMap<>(16);
        map.put("exist", redisUtils.hasKey("ip"));
        map.put("time", redisUtils.getExpire("ip"));
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    @GetMapping("/getKey")
    public ResponseEntity<Object> getKeyExpire(String str) {
        return new ResponseEntity<>(redisUtils.get(str), HttpStatus.OK);
    }

    @GetMapping("/testDelay")
    public ResponseEntity<Object> testDelay(String str) {
        return new ResponseEntity<>(redisUtils.set("order:OBJ110", 10086, 10, TimeUnit.MINUTES), HttpStatus.OK);
    }

    private final MulAccountService mulAccountService;

    @PostMapping("/insertMul")
    public ResponseEntity<Object> insertMul(@RequestBody MulAccountModel model) {
        model.setCreateTime(LocalDateTime.now());
        return new ResponseEntity<>(mulAccountService.saveOrUpdateByMultiId(model), HttpStatus.OK);
    }

    @GetMapping("/getMul")
    public ResponseEntity<Object> getMul(String name) {
        return new ResponseEntity<>(mulAccountService.getOne(new LambdaQueryWrapper<MulAccountModel>()
                .eq(MulAccountModel::getName, name)), HttpStatus.OK);
    }
}
